<template>
  <div>
    <div class="yourName">
      <div>
        <van-nav-bar
          :title="store.state.targetUser.username"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </div>
    </div>
    <div class="chatContent" @click="hide">
      <ul>
        <li
          v-for="(data, index) of messageList"
          :key="index"
          :class="{
            sent: data.fromUsername === store.state.username,
            received: data.fromUsername !== store.state.username,
          }"
        >
          <div class="chatbox">
            <p
              style="
                text-align: center;
                font-size: 12px;
                color: #ccc;
                width: 100%;
                height: 20px;
              "
            >
              {{ dayjs(new Date(data.dateTime)).format("YYYY-MM-DD HH:mm:ss") }}
            </p>
            <br />
            <span class="message-text">{{ data.msg }}</span>
          </div>
        </li>
      </ul>
    </div>
    <div class="chatSend1" v-show="flag === false">
      <div
        class="sendContent"
        style="display: flex; justify-content: space-around"
      >
        <div>
          <van-icon @click="showInfo" style="font-size: 30px" name="add-o" />
        </div>
        <div>
          <input
            @focus="sendok"
            @blur="sendcancel"
            type="text"
            v-model="store.state.msgText"
          />
        </div>
        <div style="display: flex; gap: 5px">
          <div>
            <van-icon
              @click="showEnjoy"
              style="font-size: 30px"
              name="smile-o"
            />
          </div>
          <button @click="sendText">发送</button>
        </div>
      </div>
      <div class="infoChat">
        <div class="infoChatContent" v-show="show === false">
          <div class="item">
            <van-icon style="font-size: 24px" name="photo" @click="sendImg" />
            <br />
            <p style="font-size: 12px">图片</p>
            <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileUpload" />
          </div>

          <div class="item">
            <van-icon style="font-size: 24px" name="photograph" />
            <br />
            <p style="font-size: 12px">视频</p>
          </div>
          <div class="item">
            <van-icon style="font-size: 24px" name="video" />
            <br />
            <p style="font-size: 12px" @click="video">视频聊天</p>
          </div>
          <div class="item">
            <van-icon style="font-size: 24px" name="location" />
            <br />
            <p style="font-size: 12px">位置</p>
          </div>
        </div>
        <div
          v-show="show == true"
          style="display: flex; gap: 33px"
          v-for="(item, index) in enjoy"
          :key="index"
        >
          <div
            v-for="item1 in item"
            @click="store.state.msgText += item1"
            :key="item1"
          >
            {{ item1 }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, computed } from "vue";
import { useRoute } from "vue-router";
import { io } from "socket.io-client";
import axios from "axios";
import dayjs from "dayjs";
import { useCounterStore } from "../../../../stores/counter";

const show = ref(true);
const flag = ref(false);
const sendCancel = ref(true);
const value = ref("");
const route = useRoute();
const enjoy = ref([
  ["😱", "😵", "😡", "😠", "😷", "🤒", "🤕"],
  ["😀", "😁", "😂", "🤣", "😃", "😅", "😆"],
  ["😉", "😊", "😋", "😎", "😍", "😘", "😗"],
  ["😙", "😚", "🙂", "🤗", "🤔", "😐", "😑"],
  ["😶", "🙄", "😏", "😣", "😥", "😮", "🤐"],
  ["😯", "😪", "😫", "😴", "😌", "😛", "😜"],
  ["😝", "🤤", "😒", "😓", "😔", "😕", "🙃"],
  ["🤑", "😲", "🙁", "😖", "😟", "😤", "😢"],
  ["😭", "😧", "😨", "😩", "😬", "😰", "😳"],
]);
const onClickLeft = () => history.back();
const props = defineProps({
  userId: String,
  toUsername: String,
});
const userId = ref(null);
const toUsername = ref(null);
const store = useCounterStore();

// 检测网络连接状态
const onNetworkChange = () => {
  if (navigator.onLine) {
    // 网络连接恢复，可以进行一些操作，比如重新连接 socket
  } else {
    // 网络断开，进行相应处理
  }
};

onMounted(() => {
  window.addEventListener("online", onNetworkChange);
  window.addEventListener("offline", onNetworkChange);
  if (route.query.userId || route.query.toUsername) {
    userId.value = route.query.userId;
  } else {
    userId.value = props.userId;
  }
});
const showInfo = () => {
  show.value = false;
};
const showEnjoy = () => {
  show.value = true;
  flag.value = true;
};
const hide = () => {
  flag.value = false;
};
const sendok = () => {
  sendCancel.value = false;
};
const sendcancel = () => {
  sendCancel.value = true;
};
const text = ref("");

const sendEnjoy = (item) => {
  text.value = item;
};
const sendText = () => {
  let msg = (store.state.msgText += text.value);
  store.sendMessage(msg);
  store.state.msgText = "";
  console.log(msg);
  
};

const messageList = computed(() => {
  return store.state.messageBox[store.state.username] && store.state.targetUser
    ? store.state.messageBox[store.state.username].filter((item) => {
        return (
          item.fromUsername === store.state.targetUser.username ||
          item.toUsername === store.state.targetUser.username
        );
      })
    : [];
});
console.log(messageList.value, "xixixi");

const fileInput = ref(null);
const sendImg = () => {
  if(navigator.onLine){
    fileInput.value.click()
  }else{
    console.log("网络已断开");
  }
};
const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  console.log(file, "file");
  if (file) {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('fromUsername', store.state.username);
    try {
      const response = await axios.post('http://localhost:3000/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log(response.data, '上传成功');
      
      // 假设后端返回了文件的URL或路径
      const imageUrl = response.data.url; // 根据后端实际返回的字段名调整
      
      
      // 构造图片消息并通过Socket.io发送
      store.sendMessage({
        msg: `<img src="${imageUrl}" />`,
        fromUsername: store.state.username,
        toUsername: store.state.targetUser?.username, // 确保targetUser已经设置
        dateTime: new Date().toISOString(), // 或使用后端生成的时间戳
        // 可能还需要其他字段，如targetId等，根据后端需求添加
      });
      
      // 注意：这里我们没有直接在UI上显示图片，因为图片消息已经通过Socket.io发送，
      // 其他用户（包括当前用户，如果他们在不同的聊天窗口中）将收到这条消息并在他们的UI上显示。
      
    } catch (error) {
      console.log(error, '上传失败');
    }
  }
};

const video = () => {
  //跳转到视频聊天
  window.location.href = "/videoCall?userId=";
}

</script>

<style lang="scss" scoped>
.chatContent ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.chatContent li {
  margin-bottom: 10px;
  line-height: 30px;
}

.chatbox {
  width: 100%;
  height: 100px;
  // border: 1px solid #ccc;
}

.message-text {
  display: block;
  padding: 10px;
  border-radius: 5px;
  max-width: 70%; /* 限制消息的最大宽度 */
}

.sent .message-text {
  text-align: right;
  float: right;
  background-color: #dcf8c6; /* 发送消息的背景色 */
}

.received .message-text {
  text-align: left;
  float: left;
  background-color: #e0e0e0; /* 接收消息的背景色 */
}

/* 可选：为时间戳添加样式 */
.chatContent p {
  color: #888;
  font-size: 0.875em;
  margin-bottom: 5px;
}
.chatSend {
  width: 100%;
  height: 110px;
  background-color: #f5f5f5;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .commonWordsContent {
    height: 40px;
    display: flex;
    // background-color: antiquewhite;
    .wordItems {
      width: 90px;
      height: 40px;
      border-radius: 10px;
      background-color: #fff;
      margin: 5px;
      text-align: center;
      line-height: 40px;
      font-size: 14px;
      // color: #000;
    }
  }
}
button {
  width: 60px;
  height: 35px;
  border: none;
  border: 1px solid greenyellow;
  background-color: rgb(44, 248, 33);
  color: white;
  border-radius: 10px;
  text-align: center;
  line-height: 15px;
  margin-top: 10px;
}

.chatSend1 {
  width: 100%;
  height: 110px;
  background-color: #f5f5f5;
  // position: fixed;
  // bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .commonWordsContent {
    height: 40px;
    display: flex;
    // background-color: antiquewhite;
    .wordItems {
      width: 90px;
      height: 40px;
      border-radius: 10px;
      background-color: #fff;
      margin: 5px;
      text-align: center;
      line-height: 40px;
      font-size: 14px;
      // color: #000;
    }
  }
}

.sendContent {
  width: 100%;
  height: 60px;
  //   background-color: #e56767;
  line-height: 60px;
  input {
    width: 220px;
    height: 40px;
    border-radius: 10px;
    border: none;
    outline: none;
    padding-left: 10px;
  }
}

.chatContent {
  width: 100%;
  height: calc(100vh - 46px - 110px - 150px);
}

.infoChat {
  width: 100%;
  height: 150px;
  position: fixed;
  bottom: 0;
  background-color: #f5f5f5;
}

.infoChatContent {
  width: 95%;
  height: 100px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  .item {
    width: 50px;
    height: 50px;
    background-color: #fff;
    text-align: center;
    line-height: 50px;
    margin: 10px;
  }
}
</style>